/**
 * 入参
 * 组合ID fundCode
 * 时间戳 timeStamp
 * 存款类型（枚举数据源）typeList
 * 存款总行（枚举数据源） headBankList
 * 出参
 * 响应onDoubleClick事件，抛出当前行数据
 *
 */
import React, { PureComponent } from 'react';
import { SelectC, TableC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Modal } from 'antd';
import style from './index.less';
import config from './config';

const confirm = Modal.confirm;
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import moment from 'moment';
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 10, offset: 0 },
    xxl: { span: 8, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 13, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};

@connect(({ depositOrderM, userM: user, globalM, loading }) => ({
  depositOrderM,
  user,
  globalM,
  loading,
}))
@Form.create()
export default class Hold extends PureComponent {
  state = {
    columns: undefined,
    dataSource: undefined, //持仓数据
    currentPage: 1, //页码
    numInPage: 20, //每页条数
    pageInfo: {}, //后端返回的页码信息
    headBankList: [], //存款总行列表
    headBankNameSearch: undefined, //当前输入总行的值
    isQuery: true, //是否点击了查询
    fundCode: undefined, //组合id
    timeStamp: undefined, //时间戳
  };
  componentDidMount() {}
  UNSAFE_componentWillReceiveProps(nextProps) {
    //组合ID和时间戳变更时，重新调用接口
    if (nextProps.fundCode !== this.state.fundCode || nextProps.timeStamp !== this.state.timeStamp) {
      this.setState(
        {
          fundCode: nextProps.fundCode,
          timeStamp: nextProps.timeStamp,
        },
        () => {
          if (nextProps.fundCode) {
            this.queryTableList();
          }
        },
      );
    }
    if (nextProps.productId !== this.state.productId) {
      this.setState(
        {
          productId: nextProps.productId,
        },
        () => {
          if (nextProps.productId) {
            //获取存款总行 清空选中项

            this.getHeadBankList(undefined);
          }
        },
      );
    }
  }

  //查询表格数据
  queryTableList = () => {
    const { numInPage, currentPage, fundCode } = this.state;
    this.setState({
      columns: undefined,
      dataSource: undefined, //产品信息
      pageInfo: {},
    }); //查询之前清除数据
    const values = this.props.form.getFieldsValue();
    const params = {
      fundCode,
      currentPage,
      numInPage,
    };
    if (values.depositType) {
      params.depositType = values.depositType;
    }
    if (values.bankHeadOfficeNameId) {
      params.bankHeadOfficeNameId = values.bankHeadOfficeNameId;
    }
    if (this.props.type == 10) {
      //交易录入的字段 type=10
      params.listId = params.fundCode;
      delete params.fundCode;
    }
    this.props.dispatch({
      type: this.props.type != 10 ? 'depositOrderM/getPosition' : 'depositOrderM/getPositionTrade', //交易录入单独请求type=10
      payload: {
        ...params,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.dataSource.map((item, key) => {
            item.key = key;
          });
          this.setState({
            columns: JSON.parse(JSON.stringify(config.holdColumns)) || [],
            dataSource: data.dataSource || [],
            pageInfo: data.pageInfo || {},
          });
        } else {
          this.setState({
            columns: [],
            dataSource: [],
            pageInfo: {},
          });
        }
      },
    });
  };

  //表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryTableList();
      },
    );
  };
  formatData = (key, arr) => {
    //翻译存款类型
    if (key == null) return '--';
    let title = '';
    arr.map((item) => {
      if (item.code == key) {
        title = item.value;
      }
    });
    return title;
  };
  //表格列表
  initTable = () => {
    const { currentPage, numInPage, columns, dataSource, pageInfo } = this.state;
    const {
      globalM: {
        dataDictionary: { CKLX = [] },
      },
    } = this.props;
    columns &&
      columns.map((item) => {
        if (item.key == 'bankDepositBalance') {
          item.type = 'money';
        }
        if (item.key == 'bankDepositRate') {
          item.align = 'right';
          item.render = (text, record) => {
            return text !== null ? text.toFixed(2) + '%' : '--';
          };
        }
        if (item.key == 'bankStartDate' || item.key == 'bankEndDate') {
          item.render = (text, record) => {
            return text !== null ? moment(text).format('YYYY-MM-DD') : '--';
          };
        }
        if (item.key == 'isAdvanceInterest') {
          item.render = (text, record) => {
            return text !== null ? (text == 1 ? '否' : '是') : '--';
          };
        }
        if (item.key == 'depositType') {
          item.render = (text, record) => {
            return this.formatData(text, CKLX);
          };
        }
      });
    if (this.props.type == '10' && columns && columns[0]?.key == 'investmentType') {
      columns.shift();
    }
    return (
      <TableC
        columns={columns}
        dataSource={dataSource}
        onChange={this.handleTableChange}
        onRow={(record) => {
          return {
            onDoubleClick: (event) => {
              //响应onDoubleClick事件，抛出当前行数据
              this.props.doubleClick(record);
              this.setState({
                rowData: record,
              });
            },
          };
        }}
        current={currentPage}
        total={pageInfo.total || 0}
        pageSize={numInPage}
        rowKey='key'
      />
    );
  };
  //select变更即查询持仓列表
  selectChange = (e, type) => {
    this.props.form.setFieldsValue({
      [type]: e,
    });
    if (type == 'depositType') this.getHeadBankList();
    if (this.state.fundCode) this.queryTableList();
  };
  //模糊查询总行列表
  getHeadBankList = (e) => {
    const { dispatch } = this.props;
    this.props.form.setFieldsValue({
      bankHeadOfficeNameId: undefined,
    });
    this.setState({
      headBankNameSearch: e,
    });
    const params = {};
    if (e && e != false) params.value = e; //入参有值传入后端
    this.timer ? clearTimeout(this.timer) : '';
    this.timer = setTimeout(() => {
      dispatch({
        type: 'depositOrderM/getHeadBankList',
        payload: {
          productId: this.state.productId,
          accountType: this.props.form.getFieldsValue().depositType ? this.props.form.getFieldsValue().depositType : '',
          ...params,
        },
        callback: (type, val, data) => {
          if (type == 'success') {
            if (val == this.state.headBankNameSearch) {
              //防止上一次延迟返回 赋值到本次查询中
              this.setState({
                headBankList: data,
              });
            }
          } else {
            if (val == this.state.headBankNameSearch) {
              this.setState({
                headBankList: [],
              });
            }
          }
        },
      });
    }, 500);
  };
  //查询form
  topTool = () => {
    const { typeList } = this.props;
    const { headBankList } = this.state;
    const {
      globalM: {
        dataDictionary: { CKLX = [] },
      },
    } = this.props;

    return (
      <div>
        <Row>
          <Col span={6}>
            <SelectC
              form={this.props.form} // form对象
              title='存款类型' // 显示名称
              dataIndex='depositType' // Form识别的Item ID
              dataSource={CKLX.map((item) => {
                return { value: item.code, title: item.value };
              })}
              isMultiple={false}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              onChange={(e) => this.selectChange(e, 'depositType')}
              allowClear={true}
            />
          </Col>
          <Col span={6}>
            <SelectC
              form={this.props.form} // form对象
              title='存款总行' // 显示名称
              dataIndex='bankHeadOfficeNameId' // Form识别的Item ID
              dataSource={headBankList.map((item) => {
                return { value: item.bankNo, title: item.bankName };
              })}
              isMultiple={false}
              optionTitle={true}
              showSearch={true}
              formItemLayout={FormItemLayout}
              onSearch={this.getHeadBankList}
              filterOption={false}
              onChange={(e) => this.selectChange(e, 'bankHeadOfficeNameId')}
              placeholder={'请输入'}
              allowClear={true}
            />
          </Col>
        </Row>
      </div>
    );
  };

  render() {
    const { fundCode } = this.state;
    return (
      <div className={'hold'}>
        {this.props.type != 10 ? this.topTool() : null}
        {fundCode ? this.initTable() : null}
      </div>
    );
  }
}
